import mqtt from'../../utils/mqtt';
const aliyunOpt = require('../../utils/aliyun/aliyun_connect.js');

let that = null;
Page({
    data:{
      kook:0,

      //设置温度值和湿度值 
      // temperature:"",
      humidity:"",
      humidity0:"",
      humidity1:"",
      humidity2:"",
      num0:"",
      num1:"",
      num2:"",

      client:null,//记录重连的次数
      reconnectCounts:0,//MQTT连接的配置
      options:{
        protocolVersion: 4, //MQTT连接协议版本
        clean: false,
        reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
        connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
        resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
        clientId: '',
        password: '',
        username: '',
      },

      aliyunInfo: {
        productKey: 'k0fupjeRoVc', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
        deviceName: 'wechat', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
        deviceSecret: '5538f7b966afb05c12ac1a6c632ad866', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
        regionId: 'cn-shanghai', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
        pubTopic: '/k0fupjeRoVc/wechat/user/date', //发布消息的主题
        subTopic: '/k0fupjeRoVc/wechat/user/undate', //订阅消息的主题
      },
    },

  onLoad:function(){
    that = this;
    wx.startPullDownRefresh();
    // console.log("1111");
    // 传湿度

    // this.data.humidity=wx.getStorageSync('hum');


    this.data.humidity0=wx.getStorageSync('hum');
    this.data.humidity1=wx.getStorageSync('hum1');
    this.data.humidity2=wx.getStorageSync('hum2');


    console.log(this.data.humidity0);
    console.log(this.data.humidity1);
    console.log(this.data.humidity2);
    
    // judge
    if (this.data.humidity0>70) {
      this.setData({
        num0:0
      })
    }
    if (this.data.humidity0<70&&this.data.humidity0>30) {
      this.setData({
        num0:1
      })
    }
    if (this.data.humidity0<30) {
      this.setData({
        num0:2
      })
    }
// tomorrow
  if (this.data.humidity1>70) {
    this.setData({
      num1:0
    })
  }
  if (this.data.humidity1<70&&this.data.humidity1>30) {
    this.setData({
      num1:1
    })
  }
  if (this.data.humidity0<30) {
    this.setData({
      num1:2
    })
  }
// tdat
  if (this.data.humidity2>95) {
    this.setData({
      num2:0
    })
  }
  if (this.data.humidity2<95&&this.data.humidity2>90) {
    this.setData({
      num2:1
    })
  }
  if (this.data.humidity2<90) {
    this.setData({
      num2:2
    })
  }




    let clientOpt = aliyunOpt.getAliyunIotMqttClient({
      productKey: that.data.aliyunInfo.productKey,
      deviceName: that.data.aliyunInfo.deviceName,
      deviceSecret: that.data.aliyunInfo.deviceSecret,
      regionId: that.data.aliyunInfo.regionId,
      port: that.data.aliyunInfo.port,
    });

    console.log("get data:" + JSON.stringify(clientOpt));
    let host = 'wxs://' + clientOpt.host;
    
    this.setData({
      'options.clientId': clientOpt.clientId,
      'options.password': clientOpt.password,
      'options.username': clientOpt.username,
    })
    console.log("this.data.options host:" + host);
    console.log("this.data.options data:" + JSON.stringify(this.data.options));

    //访问服务器
    this.data.client = mqtt.connect(host, this.data.options);

    this.data.client.on('connect', function (connack) {
      wx.showToast({
        title: '登录成功'
      })
      console.log("登录成功");
    })


//接收消息监听
    that.data.client.on("message", function (topic, payload) {
      //message是一个16进制的字节流
      let dataFromALY = {};
      try {
        dataFromALY = JSON.parse(payload);
        console.log(dataFromALY);
        that.setData({
          //转换成JSON格式的数据进行读取
          kook:dataFromALY.kook,
        })

      } catch (error) {
          console.log(error);
        }
      wx.showModal({
        content: " 收到topic:[" + topic + "], payload :[" + payload + "]",
        showCancel: false,
      }); 
    // wx.setStorageSync('kook', this.data.kook);
      
    })

    //服务器连接异常的回调
    that.data.client.on("error", function (error) {
      console.log(" 服务器 error 的回调" + error)

    })
    //服务器重连连接异常的回调
    that.data.client.on("reconnect", function () {
      console.log(" 服务器 reconnect的回调")

    })
    //服务器连接异常的回调
    that.data.client.on("offline", function (errr) {
      console.log(" 服务器offline的回调")
    })

    
  },

  onReady: function () {
// 发数据
    that.sendCommond('set', this.data.num0,this.data.num1,this.data.num2);

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log(this.data.kook);
    wx.setStorageSync('kook', this.data.kook)
  },
  
  
  onClickOpen() {
    that.sendCommond('set', this.data.num0,this.data.num1,this.data.num2);
  },
  onClickOff() {
    that.sendCommond('set', 0);
  },
  // sendCommond(cmd, data) {
  //   let sendData = {
  //     cmd: cmd,
  //     data: data
  //   };
  sendCommond(cmd, today,tomorrow,tdat) {
    let sendData = {
      cmd: cmd,
      today: today,
      tomorrow: tomorrow,
      tdat: tdat
    };

//此函数是订阅的函数，因为放在访问服务器的函数后面没法成功订阅topic，因此把他放在这个确保订阅topic的时候已成功连接服务器
//订阅消息函数，订阅一次即可 如果云端没有订阅的话，需要取消注释，等待成功连接服务器之后，在随便点击（开灯）或（关灯）就可以订阅函数
    // this.data.client.subscribe(this.data.aliyunInfo.subTopic,function(err){
    //   if(!err){
    //     console.log("订阅成功");
    //   };
    //   wx.showModal({
    //     content: "订阅成功",
    //     showCancel: false,
    //   })
    // })
    

    //发布消息
    if (this.data.client && this.data.client.connected) {
      this.data.client.publish(this.data.aliyunInfo.pubTopic, JSON.stringify(sendData));
      console.log("************************")
      console.log(this.data.aliyunInfo.pubTopic)
      console.log(JSON.stringify(sendData))
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  }
})